﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace LF.Application.Helpers
{
    public class JwtHelper
    {

        public static string Validate(Claim?[] claims)
        {
            var jwtConfig = LFConfig.Jwt;
            // 2 设置SecretKey
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey));

            // 3 设置加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;

            // 4 生成签名凭证信息
            var signingCredentials = new SigningCredentials(secretKey, algorithm);

            // 5 设置Token过期时间
            var expires = DateTime.Now.AddHours(jwtConfig.Expire);

            // 6 生成token
            var securityToken = new JwtSecurityToken(
                claims: claims,
                issuer: jwtConfig.Issuer,
                audience: jwtConfig.Audience,
                notBefore: DateTime.Now,
                expires: expires,
                signingCredentials: signingCredentials
            );

            var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
            var token = jwtSecurityTokenHandler.WriteToken(securityToken);
            return token;
        }
    }
}
